import { createRouter, createWebHistory } from 'vue-router'
import Dashboard from '@/views/Dashboard.vue'

const routes = [
  {
    path: '/',
    component: Dashboard,
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: () => import('@/views/Home.vue')
      },
      {
        path: 'family',
        component: () => import('@/views/Family.vue')
      },
      {
        path: 'room',
        component: () => import('@/views/Room.vue')
      },
      {
        path: 'sensor',
        component: () => import('@/views/Sensor.vue')
      },
      {
        path: 'air-data',
        component: () => import('@/views/AirData.vue')
      },
      {
        path: 'analysis/bar',
        component: () => import('@/views/analysis/BarChart.vue')
      },
      {
        path: 'analysis/line',
        component: () => import('@/views/analysis/LineChart.vue')
      },
      {
        path: 'alarm',
        component: () => import('@/views/Alarm.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue')
  },
  {
    path: '/forget',
    name: 'Forget',
    component: () => import('@/views/Forget.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  if (to.path !== '/login' && !token) {
    next('/login')
  } else {
    next()
  }
})

export default router
